package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.moyun.modelclass.adapter.ModelDeleteAdapter;
import com.moyun.modelclass.adapter.SearchPopularAdapter;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.dialog.AssociationModelDialog;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.AppArticleDetailsApi;
import com.moyun.modelclass.http.api.AppModelListApi;
import com.moyun.modelclass.http.api.ArticleRemoveApi;
import com.moyun.modelclass.http.api.EditArticleApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.bean.ModelResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.CreateFileUtils;
import com.moyun.modelclass.utils.GlideEngine;
import com.moyun.modelclass.utils.RichEditor;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.moyun.modelclass.view.MyEditText;
import com.moyun.modelclass.view.TBFoldLayout;
import com.moyun.modelclass.view.recyclerview.DividerItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 作者：Meteor
 * tip：编辑文章
 */
public class EditArticleActivity extends BaseActivity implements ModelDeleteAdapter.OnDeleteClick {
    private RelativeLayout llEditArticleTop;
    private ImageView ivEditArticleBack;
    private ImageView ivEditArticleDelete;
    private MyEditText etEditArticleTitle;
    private TextView etEditArticleTitleLength;

    private FrameLayout flEditArticleAdd;
    private RichEditor etEditArticleContent;
    private TextView tvEditArticleAssociationModel;
    private View viewEditArticleAssociationModel;
    private RecyclerView recyclerEditArticleAssociationModel;
    private TextView tvAddArticlePopular;
    private View viewAddArticlePopular;
    private TextView tvEditArticlePopular;
    private TBFoldLayout foldEditArticlePopular;
    private TextView tvEditArticleSaveDraft;
    private TextView tvEditArticlePreview;
    private TextView tvEditArticleIssue;

    private ModelDeleteAdapter modelDeleteAdapter = new ModelDeleteAdapter();
    private SearchPopularAdapter searchPopularAdapter = new SearchPopularAdapter();
    private List<ModelResponse> mModelCheckList = new ArrayList<>();

    private File otherFile = null;//其他图片临时文件
    public static final int REQUEST_CODE = 1003;
    public static final String KEY_POPULAR_ID = "KEY_POPULAR_ID";
    private String mArticleId = "";//文章id

    public static void start(Context context, String articleId) {
        Intent starter = new Intent(context, EditArticleActivity.class);
        starter.putExtra("articleId", articleId);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_edit_article;
    }

    @Override
    protected void assignViews() {
        llEditArticleTop = (RelativeLayout) findViewById(R.id.ll_edit_article_top);
        ivEditArticleBack = (ImageView) findViewById(R.id.iv_edit_article_back);
        ivEditArticleDelete = (ImageView) findViewById(R.id.iv_edit_article_delete);
        etEditArticleTitle = (MyEditText) findViewById(R.id.et_edit_article_title);
        etEditArticleTitleLength = (TextView) findViewById(R.id.et_edit_article_title_length);

        flEditArticleAdd = (FrameLayout) findViewById(R.id.fl_edit_article_add);
        etEditArticleContent = (RichEditor) findViewById(R.id.et_edit_article_content);
        tvEditArticleAssociationModel = (TextView) findViewById(R.id.tv_edit_article_association_model);
        viewEditArticleAssociationModel = (View) findViewById(R.id.view_edit_article_association_model);
        recyclerEditArticleAssociationModel = (RecyclerView) findViewById(R.id.recycler_edit_article_association_model);
        tvAddArticlePopular = (TextView) findViewById(R.id.tv_add_article_popular);


        viewAddArticlePopular = (View) findViewById(R.id.view_add_article_popular);
        tvEditArticlePopular = (TextView) findViewById(R.id.tv_edit_article_popular);
        foldEditArticlePopular = (TBFoldLayout) findViewById(R.id.fold_edit_article_popular);
        tvEditArticleSaveDraft = (TextView) findViewById(R.id.tv_edit_article_save_draft);
        tvEditArticlePreview = (TextView) findViewById(R.id.tv_edit_article_preview);
        tvEditArticleIssue = (TextView) findViewById(R.id.tv_edit_article_issue);


        StatusBarUtil.setPaddingSmart(this, llEditArticleTop);

        recyclerEditArticleAssociationModel.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerEditArticleAssociationModel.addItemDecoration(new DividerItemDecoration(mContext, Color.parseColor("#EFEFEF"), 1, SizeUtils.dp2px(6), SizeUtils.dp2px(6), false));
        modelDeleteAdapter.setOnDeleteClick(this);
        recyclerEditArticleAssociationModel.setAdapter(modelDeleteAdapter);

        foldEditArticlePopular.setAdapter(searchPopularAdapter);

        etEditArticleTitleLength.setText(getString(R.string.evaluate_content_length, 0));
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivEditArticleBack, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ClickUtils.applySingleDebouncing(ivEditArticleDelete, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeArticle();
            }
        });

        ClickUtils.applySingleDebouncing(tvEditArticleAssociationModel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AssociationModelDialog dialog = AssociationModelDialog.getInstance(mActivity, new AssociationModelDialog.OnModelListListener() {
                    @Override
                    public void content(List<ModelResponse> modelResponseList) {
                        mModelCheckList = modelResponseList;
                        viewEditArticleAssociationModel.setVisibility(View.VISIBLE);
                        modelDeleteAdapter.setList(modelResponseList);
                    }

                    @Override
                    public void cancel() {

                    }
                }).builder();
                dialog.show();
            }
        });

        etEditArticleTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                etEditArticleTitleLength.setText(getString(R.string.evaluate_content_length, s.toString().length()));
            }
        });

        ClickUtils.applySingleDebouncing(flEditArticleAdd, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                XXPermissions.with(EditArticleActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                PictureSelector.create(EditArticleActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .setImageEngine(GlideEngine.createGlideEngine())
                                        .setMaxSelectNum(1)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(ArrayList<LocalMedia> result) {
                                                for (LocalMedia media : result) {
                                                    Luban.with(EditArticleActivity.this)
                                                            .load(media.getRealPath())
                                                            .ignoreBy(50)
                                                            .setTargetDir(CreateFileUtils.getSandboxPath(EditArticleActivity.this))
                                                            .setCompressListener(new OnCompressListener() {
                                                                                     @Override
                                                                                     public void onStart() {
                                                                                     }

                                                                                     @Override
                                                                                     public void onSuccess(int index, File compressFile) {
                                                                                         otherFile = compressFile;
                                                                                         initUpdateImageApi(true);
                                                                                     }

                                                                                     @Override
                                                                                     public void onError(int index, Throwable e) {
                                                                                     }
                                                                                 }
                                                            ).launch();
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                ToastUtils.showShort("获取存储权限失败");
                            }
                        });
            }
        });

        ClickUtils.applySingleDebouncing(tvAddArticlePopular, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditPopularActivity.start(EditArticleActivity.this, searchPopularAdapter.getData(), REQUEST_CODE);
            }
        });

        ClickUtils.applySingleDebouncing(tvEditArticleSaveDraft, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitArticle(true);
            }
        });

        ClickUtils.applySingleDebouncing(tvEditArticlePreview, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                articlePreview();
            }
        });

        ClickUtils.applySingleDebouncing(tvEditArticleIssue, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitArticle(false);
            }
        });
    }

    private void articlePreview() {
        String title = etEditArticleTitle.getText().toString().trim();
        String htmlString = etEditArticleContent.getHtml();
        String content = "";
        if (htmlString != null && !htmlString.isEmpty()) {
            content = htmlString
                    .replaceAll("<img src=\"http://res-t.mo-yun.com/", "[image:")
                    .replaceAll("-0\\*0.jpg\">", "]")
                    .replaceAll("<div>", "")
                    .replaceAll("</div>", "")
                    .replaceAll("<br>", "");
        }

        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort("请输入标题");
            return;
        }

        if (TextUtils.isEmpty(content)) {
            ToastUtils.showShort("请输入文章正文");
            return;
        }
        if ((mModelCheckList == null || mModelCheckList.size() == 0)) {
            ToastUtils.showShort("请关联模型");
            return;
        }

        List<String> modelList = new ArrayList<>();
        if (mModelCheckList != null && mModelCheckList.size() > 0) {
            for (ModelResponse modelResponse : mModelCheckList) {
                modelList.add(modelResponse.getId());
            }
        }

        List<String> topicList = searchPopularAdapter.getData();
        ArticlePreviewActivity.start(this, title, content, topicList, modelList);
    }

    private void submitArticle(boolean isDraft) {
        String title = etEditArticleTitle.getText().toString().trim();
        String htmlString = etEditArticleContent.getHtml();
        String content = "";
        if (htmlString != null && !htmlString.isEmpty()) {
            content = htmlString
                    .replaceAll("<img src=\"http://res-t.mo-yun.com/", "[image:")
                    .replaceAll("-0\\*0.jpg\">", "]")
                    .replaceAll("<div>", "")
                    .replaceAll("</div>", "")
                    .replaceAll("<br>", "");
        }

        if (TextUtils.isEmpty(title) && !isDraft) {
            ToastUtils.showShort("请输入标题");
            return;
        }

        if (!content.contains("[image:image/") && !isDraft) {
            ToastUtils.showShort("请至少选择一张图片");
            return;
        }

        if (TextUtils.isEmpty(content) && !isDraft) {
            ToastUtils.showShort("请输入文章正文");
            return;
        }
        if ((mModelCheckList == null || mModelCheckList.size() == 0) && !isDraft) {
            ToastUtils.showShort("请关联模型");
            return;
        }

        List<String> modelList = new ArrayList<>();
        if (mModelCheckList != null && mModelCheckList.size() > 0) {
            for (ModelResponse modelResponse : mModelCheckList) {
                modelList.add(modelResponse.getId());
            }
        }
        List<String> topicList = new ArrayList<>();
        if (searchPopularAdapter.getData() != null && searchPopularAdapter.getData().size() > 0) {
            topicList = searchPopularAdapter.getData();
        }
        initSaveArticleApi(mArticleId, title, "", content, modelList, topicList, isDraft);
    }

    @Override
    protected void getExtras(Bundle bundle) {
        mArticleId = bundle.getString("articleId", "");
        if (mArticleId == null || mArticleId.isEmpty()) {
            ivEditArticleDelete.setVisibility(View.GONE);
        } else {
            ivEditArticleDelete.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initArticleDetailsLog();
    }

    //文章详情
    private void initArticleDetailsLog() {
        if (mArticleId == null || mArticleId.isEmpty()) {
            return;
        }
        EasyHttp.post(this)
                .api(new AppArticleDetailsApi().setArticleId(mArticleId))
                .request(new HttpCallback<HttpData<AppArticleDetailsApi.Bean>>(this) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(HttpData<AppArticleDetailsApi.Bean> result) {
                        if (result != null && result.getData() != null) {
                            etEditArticleTitle.setText(result.getData().getTitle());
                            setContent(result.getData().getContent());

                            initModelListLog(result.getData().getModelList());
                            searchPopularAdapter.setNewData(result.getData().getTags());
                        }
                    }
                });
    }

    private void setContent(String content) {
        //正则表达式匹配文本内容
        String stringRegex = "[^\\[\\]]+";
        Pattern stringPattern = Pattern.compile(stringRegex);
        Matcher stringMatcher = stringPattern.matcher(content);

        // 存储文本内容的列表
        List<String> stringContents = new ArrayList<>();

        // 匹配文本内容并存储到列表中
        while (stringMatcher.find()) {
            stringContents.add(stringMatcher.group().trim());
        }

        String contentString = "";
        for (String contentsData : stringContents) {
            if (contentsData.startsWith("image:image/", 0)) {
                contentString = contentString.concat(contentsData.replaceAll("image:image/", "<img src=\"http://res-t.mo-yun.com/image/")
                        .concat("-0*0.jpg\">"));
            } else {
                contentString = contentString.concat(contentsData);
            }
        }
        etEditArticleContent.setHtml(contentString);
    }

    //批量获取模型数据
    private void initModelListLog(List<String> modelIdList) {
        if (modelIdList.size() <= 0) {
            ToastUtils.showShort("模型id列表为空");
            return;
        }
        EasyHttp.post(this)
                .api(new AppModelListApi().setModelIdList(modelIdList).setScene(1))
                .request(new HttpCallback<HttpData<AppModelListApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<AppModelListApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            viewEditArticleAssociationModel.setVisibility(View.VISIBLE);
                            modelDeleteAdapter.setNewInstance(mModelCheckList = result.getData().getList());
                        }
                    }
                });
    }

    private void initSaveArticleApi(String id, String title, String simpleImage, String content, List<String> modelList, List<String> tags, boolean isDraft) {
        EasyHttp.post(this).api(new EditArticleApi()
                        .setId(id)
                        .setTitle(title)
                        .setSimpleImage(simpleImage)
                        .setContent(content)
                        .setModelList(modelList)
                        .setTags(tags)
                        .setIsDraft(isDraft))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        if (isDraft) {
                            if (CommonConfiguration.isLogin(kv)) {
                                MyArticleActivity.start(EditArticleActivity.this);
                            } else {
//                                ToastUtils.showShort(getString(R.string.http_token_error));
                                LoginVerificationCodeActivity.start(EditArticleActivity.this);
                            }
                        } else {
                            ArticleAuditActivity.start(EditArticleActivity.this);
                        }
                        finish();
                    }
                });
    }

    private void initUpdateImageApi(boolean isWatermark) {
        EasyHttp.post(this).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(otherFile)
                        .setWatermark(isWatermark))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                        etEditArticleContent.insertImage(CommonConfiguration.splitResUrl(3, result.getData().getUrl()));
                    }
                });
    }

    private void removeArticle() {
        EasyHttp.post(this)
                .api(new ArticleRemoveApi().setArticleId(mArticleId))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        ToastUtils.showShort("删除成功");
                        finish();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                ArrayList<String> mPopularList = data.getStringArrayListExtra(KEY_POPULAR_ID);
                if (mPopularList != null && mPopularList.size() > 0) {
                    searchPopularAdapter.setNewData(mPopularList);
                    viewAddArticlePopular.setVisibility(View.VISIBLE);
                    tvEditArticlePopular.setVisibility(View.VISIBLE);
                } else {
                    searchPopularAdapter.setNewData(new ArrayList<>());
                    viewAddArticlePopular.setVisibility(View.GONE);
                    tvEditArticlePopular.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void delete(int position) {
        mModelCheckList.remove(position);
        if (mModelCheckList != null && mModelCheckList.size() > 0) {
            viewEditArticleAssociationModel.setVisibility(View.VISIBLE);
            modelDeleteAdapter.setNewInstance(mModelCheckList);
        } else {
            modelDeleteAdapter.setNewInstance(new ArrayList<>());
        }
    }
}
